const { ccclass, property } = cc._decorator;

const KEY_MAX_LIMIT_ROUNDS = "MaxLimitRounds";

@ccclass
export default class ChildLockMenu extends cc.Component {

    @property(cc.SpriteAtlas)
    atlas: cc.SpriteAtlas = null;

    static instance: ChildLockMenu = null;
    
    btns: cc.Node[] = [];
    /** 玩多少局进入休息 */
    static set MaxPlayRounds(value: number) {
        localStorage.setItem(KEY_MAX_LIMIT_ROUNDS, value + '');
    }
    /** 玩多少局进入休息 */
    static get MaxPlayRounds(): number {
        let maxStr = localStorage.getItem(KEY_MAX_LIMIT_ROUNDS);
        if (maxStr) {
            return Number(maxStr);
        }
        return 10; //默认可以玩10局
    }

    onDestroy() {
        ChildLockMenu.instance = null;
    }

    onLoad() {
        ChildLockMenu.instance = this;

        this.btns.push(this.node.getChildByName('Btn01'));
        this.btns.push(this.node.getChildByName('Btn02'));
        this.btns.push(this.node.getChildByName('Btn03'));
        this.btns.push(this.node.getChildByName('Btn04'));
        
        this.btns.forEach(element => {
            element.on(cc.Node.EventType.TOUCH_START, this.onBtnTouchDown, this);
        });

        //历史设置的限制级别
        let maxRounds = ChildLockMenu.MaxPlayRounds;
        if (maxRounds == 0) {
            this.setBtnSelect(3);
        } else if (maxRounds == 1) {
            this.setBtnSelect(0);
        } else if (maxRounds == 3) {
            this.setBtnSelect(1);
        } else if (maxRounds == 10) {
            this.setBtnSelect(2);
        }
    }

    private onBtnTouchDown(e: cc.Event.EventTouch) {
        let btnNode = e.target;
        for (let i = 0; i < this.btns.length; i++) {
            if (this.btns[i] == btnNode) {
                this.setBtnSelect(i);
                break;
            }
        }
    }

    private setBtnSelect(index: number) {
        switch (index) {
            case 0:
                ChildLockMenu.MaxPlayRounds = 1;
                break;
            case 1:
                ChildLockMenu.MaxPlayRounds = 3;
                break;
            case 2:
                ChildLockMenu.MaxPlayRounds = 10;
                break;
            case 3:
                ChildLockMenu.MaxPlayRounds = 0;//无限制
                break;
        }
        for (let i = 0; i < this.btns.length; i++) {
            let frameName = 'xiuxi' + (4 - i);
            if (i == index) {
                frameName += 'x';
            }
            this.btns[i].getComponent(cc.Sprite).spriteFrame = this.atlas.getSpriteFrame(frameName);
        }
    }

}
